<?php
/*
 * 权限生成工具
 * @since 1.0 2014-7-11 by sutroon
 * @example 
 */
require 'Inc/incDbHead.php';

if (I('name')) {
//    $data_file = $_SERVER['DOCUMENT_ROOT'] . '/App/Modules/' . I('name') . '/Appres/Sqlscript/PermissionData.php';
    $data_file = $_SERVER['DOCUMENT_ROOT'] . '/Application/' . I('name') . '/ProjectResourceLibrary/SqlScript/PermissionData.php';
} else {
    $data_file = 'Data/PermissionData.php';
}

$permission_data = require $data_file;
if (!is_array($permission_data)) {
    die('内容无效!');
}

if ($action == 'showconnection') {
    $r = mysql_query("SELECT DATABASE()") or die(mysql_error());
    die('DB:' . mysql_result($r, 0));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>SoPermissionSqlGererate</title>
        <meta charset="UTF-8">
        <style type='text/css'>
            body { font-size:12px;}
            table{width:100%; border: solid 1px #CCC; border-left:none; border-bottom: none;}
            th:first-child{width:30px;}
            .th-field {width:500px;}
            th, td { padding: 5px; border:solid 1px #CCC; border-right: none; border-top: none;}
            tr.tr-alt { background-color: #efefef;}
            a { text-decoration: none;}
            fieldset{ margin-bottom:10px; width:960px;}
            fieldset textarea { width:100%; height:600px;}
        </style>
        <script type="text/javascript" src="/Public/Script/jquery-1.11.1.min.js"></script>
    </head>
    <body>
        <?php
        // 全局菜单
        include 'Inc/incMenu.php';
        // 生成语句
        $i = 1;
        $ids = array();
        echo '<fieldset><legend>Permission SQL:<a href="###" title="?name=M">(?)</a></legend><textarea cols="120" rows="6">';
        generate_insert_sql($permission_data, 1);
        echo '</textarea></fieldset>';
        echo '<textarea cols="137" rows="5">' . implode(',', $ids) . '</textarea>';
        // 生成页面文件
        if (I('q') == 'file') {
            make_page($permission_data);
        }

        /**
         * 生成权限表的插入语句
         * @global int $i
         * @param array $arr
         * @param int $n
         * @since 1.0 2014-7-11 by sutroon
         * @example generate_insert_sql($arr, 1);
         */
        function generate_insert_sql($arr, $n) {
            global $i, $ids;
            if (!$i) {
                $i = 1;
            }
            foreach ($arr as $a) {
                if (isset($a['enable']) && $a['enable'] == false) {
                    continue;
                }
                $name = $a['name'];
                $code = isset($a['code']) ? $a['code'] : '';
                $url = isset($a['url']) ? str_replace('{0}', $i, $a['url']) : '';
                $isMenu = isset($a['ismenu']) && !$a['ismenu'] ? 0 : 1;
                $parentID = $n - 1;
                echo "insert into tuser_permission (id, `name`, parent_id, code, create_time, link_url, ordinal, is_menu) values ($i, '$name', $parentID, '$code', now(), '$url', $i, $isMenu);" . PHP_EOL;
                $ids[] = $i;
                $i++;
                if (array_key_exists('sub', $a)) {
                    generate_insert_sql($a['sub'], $i);
                }
            }
        }

        /**
         * 格式化数组
         * 用于make_page函数中调用,主要处理数组中的url字段,如?s=User/admin_edit/id/{key}.html,则格式化为array($model1=>array($action1=>$name1,$action2=>$name2))
         * @param array $arr
         * @param array $arrfmt
         * @return array
         * @since 1.0 2014-7-31 by sutroon
         */
        function format_array($arr, &$arrfmt) {
            foreach ($arr as $a) {
                $url = $a['url'];
                if ($url !== '' && strpos($url, '?s=Index/index/') === false) {
                    $url = substr($url, 3);
                    $arrurl = explode('/', $url);
                    $model = $arrurl[0];
                    $action = isset($arrurl[1]) ? $arrurl[1] : '';
                    if (strpos($action, '.') !== false) {
                        $action = substr($action, 0, strpos($action, '.'));
                    }
                    $arrfmt[$model][$action] = array('name' => $a['name'], 'fields' => isset($a['fields']) ? $a['fields'] : '');
                }
                if (array_key_exists('sub', $a)) {
                    format_array($a['sub'], $arrfmt);
                }
            }
            return $arrfmt;
        }

        /**
         * 生成Action页面和视图页面文件<br />
         * Action页面命名格式：{Action}Action.class.php<br />
         * 视图页面文件放在./Temp目录里面
         * @param type $arr
         * @since 
         *      2.0 2014-7-31 by sutroon 重构
         *      1.0 2014-7-17 by sutroon 创建
         * @example make_page($arr);
         */
        function make_page($arr) {
            $date = date('Y-m-d H:i:s');
            if (!is_dir('./Temp/')) {
                mkdir('./Temp/');
            }
            format_array($arr, $arrfmt);
            var_dump($arrfmt);
            die('-');
            foreach ($arrfmt as $action => $func) {
                $content = '<?php' . PHP_EOL . '/**' . PHP_EOL . ' * ' . $action . '控制器' . PHP_EOL . ' * @since 1.0 ' . $date . ' by sutroon' . PHP_EOL . ' */' . PHP_EOL . 'class ' . $action . 'Action extends AdminPageAction {' . PHP_EOL;
                foreach ($func as $method => $name) {
                    if (!$method) {
                        $method = 'index';
                    }
                    $content .= PHP_EOL . '     /**' . PHP_EOL . '     * 显示' . $name . PHP_EOL . '     * @since 1.0 ' . $date . ' by sutroon' . PHP_EOL . '     */' . PHP_EOL . '    public function ' . $method . '() {' . PHP_EOL . '        $this->display();' . PHP_EOL . '    }' . PHP_EOL;
                    // write method file
                    if (!is_dir('./Temp/' . $action . '/')) {
                        mkdir('./Temp/' . $action . '/');
                    }
                    file_put_contents('./Temp/' . $action . '/' . $method . '.html', '<!--' . PHP_EOL . $name . PHP_EOL . '@since 1.0 ' . $date . ' by sutroon' . PHP_EOL . '-->' . PHP_EOL);
                }
                $content.='}';
                $path = './Temp/' . $action . 'Action.class.php';
                file_put_contents($path, $content);
            }
            $path = $_SERVER['SCRIPT_NAME'];
            $path = substr($path, 0, strrpos($path, '/'));
            $path = str_replace('/', '\\', $path) . '\\Temp';
            echo '<div>success! <a href="SoProjectManager.php?path=' . $_SERVER['DOCUMENT_ROOT'] . $path . '" target="_blank">[Temp]</a></div>';
        }

        // 释放资源
        unset($db);
        ?>
    </body>
    <script type="text/javascript">
        // fieldset标题点击收起或展开 2014-8-22 by sutroon
        $('legend').attr('title', '点击展开或收起').click(function () {
            $(this).next().toggle();
        })
    </script>
</html>


